#include <jni.h>
#include <string>
#include <sstream>
#include<android/log.h>
#include <unistd.h>
#include <sys/syscall.h>

#define TAG "TTTTTT" // 这个是自定义的LOG的标识
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定义LOGD类型
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定义LOGW类型
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定义LOGE类型
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定义LOGF类型

void* threadTask(){
    int i = 0;
    while (true){
        LOGD("%d %d %p\n", i, syscall(SYS_gettid), threadTask);
        i++;
        sleep(1);
    }
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_hktest1_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject jthis) {
    std::string hello = "Hello from C++";
    std::stringstream s1;
    hello.append(s1.str());
    jclass MainActivity = env->FindClass("com/example/hktest1/MainActivity");
    jmethodID onCreate = env->GetMethodID(MainActivity, "onCreate", "(Landroid/os/Bundle;)V");
    jfieldID logTextEV = env->GetFieldID(MainActivity, "logTextEV", "Landroid/widget/EditText;");
    jobject jobj = env->GetObjectField(jthis, logTextEV);

    s1 << "jthis: "<< jthis << " MainActivity:"<<MainActivity << " onCreate:"<<onCreate << " logTextEV:"<<logTextEV << " jojb: "<<jobj;
//    jmethodID toS = env->GetMethodID(env->FindClass("android/view/View"), "toString", "()Ljava/lang/String;");
    jmethodID toS = env->GetMethodID(env->FindClass("java/lang/Object"), "toString", "()Ljava/lang/String;");
    jstring a = static_cast<jstring>(env->CallObjectMethod(jobj, toS));
    jboolean isCopy = false;
    s1 << " ttt:"<< env->GetStringUTFChars(a, &isCopy) << '\n';
    s1 << env->GetStringUTFChars(static_cast<jstring>(env->CallObjectMethod(jthis, toS)), &isCopy) << '\n';
    s1 << env->NewGlobalRef(jthis) << '\n';
    s1 << env->NewGlobalRef(jthis) << '\n';
    const char *ss1;
    ss1 = s1.str().c_str();
    LOGD("%s", ss1);
    pthread_t pid;
    pthread_create(&pid, nullptr, reinterpret_cast<void *(*)(void *)>(threadTask), nullptr);
    pthread_setname_np(pid, "TTTTTT");
    return env->NewStringUTF(ss1);
}

